package com.net.redis_plus.hanlde;


import com.alibaba.fastjson.JSON;
import com.net.redis_plus.pojo.JsonData;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 全局返回json
 */
@RestControllerAdvice
public class GloableResult  implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return filter(methodParameter);
    }

    private boolean filter(MethodParameter methodParameter) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (o == null) {
            return JsonData.builderSuccess();
        }
        // 判断是ResponseData子类或其本身就返回Object o本身，因为有可能是接口返回时创建了ResponseData,这里避免再次封装
        if (o instanceof JsonData) {
            return (JsonData) o;
        }
        // String特殊处理，否则会抛异常
        if (o instanceof String) {
            return JSON.toJSON(JsonData.builderSuccess(o)).toString();
        }
        return new JsonData().builderSuccess(o);
    }
}
